﻿namespace Digitalmes.Application.Sys.Dicts.Commands;

/// <summary>
/// 更新字典数据命令。
/// </summary>
/// <param name="DictData"></param>
public record UpdateDictDataCommand(SysDictDataDto DictData) : IRequest<IResult<bool>>;

internal sealed class UpdateDictDataCommandHandler(IRepository<SysDictData> repo) : IRequestHandler<UpdateDictDataCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateDictDataCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.Id == request.DictData.Id && m.IsFixed, cancellationToken))
        {
            return Result.Failure("字典数据已固定，不能修改");
        }

        if (await repo.IsAnyAsync(m => m.Code == request.DictData.Code && m.DictId == request.DictData.DictId && m.Id != request.DictData.Id, cancellationToken))
        {
            return Result.Failure("字典数据编号已存在");
        }

        var dict = request.DictData.Adapt<SysDictData>();
        var ok = await repo.UpdateAsync(dict, m => new {
            m.Code,
            m.Value,
            m.IsFixed,
            m.Sort,
            m.Status,
            m.Remark,
            m.LastModifiedBy,
            m.LastModifiedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
